/*
 * Copyright 2010 Christopher Z. Collier
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.xorf.caveman.core;

import java.io.File;
import java.sql.DriverManager;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.Dialect;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HbmResourceRunner {
    private static Logger log = LoggerFactory.getLogger(HbmResourceRunner.class);

    private Properties configProperties;
    
    private final List<HibernateConfigResource> resources
        = new ArrayList<HibernateConfigResource>();
    
    public HbmResourceRunner(String configFilePath) {
        this(buildBaseConfiguration(configFilePath).getProperties());
    }
    
    public HbmResourceRunner(Properties configProperties) {
        this.configProperties = configProperties;
    }

    public void testConnection() {
        Configuration hibernateConfig = getConfiguration();
        
        Dialect currentDialect = Dialect.getDialect(
                hibernateConfig.getProperties());

        log.info(String.format("current dialect: %s",
        		currentDialect.getClass().getSimpleName()));

        String timestampSelect = currentDialect
        		.getCurrentTimestampSelectString();

        log.info(String.format(
        		"dialect's timestamp query: %s", timestampSelect));        
        
        SessionFactory sf = hibernateConfig.buildSessionFactory();
        Session sess = sf.openSession();

        Timestamp now = (Timestamp)sess.createSQLQuery(timestampSelect)
        	.uniqueResult();
        
        log.info(String.format("received current timestamp from database: %s", now.toString()));
    }
    
    public void run() {
        Configuration hibernateConfig = getConfiguration();
        
        for (HibernateConfigResource resource : resources)
            resource.merge(hibernateConfig);
        new SchemaExport(hibernateConfig).create(true, true);
    }

    public Properties getConfigProperties() {
        return configProperties;
    }

    public void addResource(HibernateConfigResource resource) {
        log.info(String.format("adding resource: %s", resource.toString()));
        resources.add(resource);
    }
    
    public void addResource(String resourcePath) {
        addResource(HibernateConfigResource.buildInstance(resourcePath));
    }
    
    public List<HibernateConfigResource> getResources() {
        return resources;
    }

    private Configuration getConfiguration() {
        return new Configuration().setProperties(configProperties);
    }
    
    private static Configuration buildBaseConfiguration(String configFilePath) {
        Configuration hibernateConfig = new Configuration();
        hibernateConfig.configure(new File(configFilePath));
        return hibernateConfig;
    }
}
